package com.example.demo.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo.VO.CartVO;
import com.example.demo.bean.Cart;
import com.example.demo.bean.Product;
import com.example.demo.bean.User;
import com.example.demo.service.ICartService;
import lombok.extern.log4j.Log4j;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * <p>
 *   前端控制器
 * </p>
 *
 * @author 京平笙
 * @since 2021-12-06
 */
@Controller
@RequestMapping("/cart")
public class CartController {
    private Logger log1;

    @Resource
    private ICartService cartService;

//    @RequestMapping("/test")
//    public @ResponseBody List<CartVO> showUserCart(HttpSession session,
//                                                   HttpServletRequest request){
//       Integer currentPageSize=2; Integer min=1; Integer max=99999; Integer order=0;
//        User user = new User();
//                user.setUid(1);
//                user.setUname("用户一");
//                user.setUpassword("111111");
//        return cartService.showUserCart(new Page<CartVO>(),new QueryWrapper<CartVO>());
//    }
///cart/CartSelect.do
//条件查询
    @ResponseBody
    @RequestMapping("/CartSelect.do")
    private ModelAndView cartSelect( HttpSession session, HttpServletRequest request,
                                     @RequestParam(defaultValue = "1") Integer currentPageSize,
                                     @RequestParam(defaultValue = "0") Integer min,
                                    @RequestParam(defaultValue = "99999") Integer max,
                                    @RequestParam(defaultValue = "1") Integer order)  throws Exception{
        ModelAndView modelAndView = new ModelAndView();

        Page<CartVO> voPage = new Page<>(currentPageSize,2);
        User tempUser= (User) session.getAttribute("user");
        QueryWrapper<CartVO> listQueryWrapper = new QueryWrapper<>();
                                                    listQueryWrapper.eq("c.uid",tempUser.getUid())
                                                            .ge("p.pprice*c.camount",min).le("p.pprice*c.camount",max);

       if (1==order){
           listQueryWrapper.orderByAsc("p.pprice*c.camount");
       }

        IPage<CartVO> cartVOIPage = cartService.showUserCart(voPage, listQueryWrapper);


        //        把Ipage类型转化为链表形式，并传给前端
        List<CartVO> records = cartVOIPage.getRecords();
        //总金额
        int recordsAmount=0;
        for (CartVO temp :
                records) {
            recordsAmount=recordsAmount+temp.getAmount();
        }
        int recordsTotalPrice=0;
        for (CartVO temp :
                records) {
            recordsTotalPrice=recordsTotalPrice+temp.getPrice();
        }
//        modelAndView.addObject("recordsAmount",recordsAmount);
//        modelAndView.addObject("recordsTotalPrice",recordsTotalPrice);
        modelAndView.addObject("cart_Pages",cartVOIPage.getPages());
        modelAndView.addObject("cart_Total",cartVOIPage.getTotal());
        modelAndView.addObject("cart_Current",cartVOIPage.getCurrent());

        modelAndView.setViewName("cart");
        //        传参
        modelAndView.addObject("cartVOS",records);
        modelAndView.addObject("min",min);modelAndView.addObject("max",max);
        modelAndView.addObject("order",order);
        return modelAndView;
    }
//删除单项
    @ResponseBody
    @RequestMapping("/DeleteItem.do")
    private ModelAndView deleteItem(Integer cartId, HttpServletRequest httpServletRequest,
                                    HttpSession session,ModelAndView modelAndView)  throws Exception{
        UpdateWrapper<Cart> cartUpdateWrapper =new UpdateWrapper<>() ;
        System.out.println(cartId);
        System.out.println(httpServletRequest.getParameter("cartId"));
//        cartUpdateWrapper.eq("id",httpServletRequest.getParameter("thisCartId"));
        if (cartService.remove(new QueryWrapper<Cart>().eq("cid",httpServletRequest.getParameter("cartId")))){
            modelAndView.setViewName("redirect:/cart/CartSelect.do");
        }else {
            modelAndView.setViewName("redirect:/cart");
        }
        return modelAndView;
    }
//删除全部
    @ResponseBody
    @RequestMapping("/DeleteAll.do")
    private ModelAndView DeleteAll(Integer uid,
                                   HttpServletRequest httpServletRequest,ModelAndView modelAndView)  throws Exception{
        System.out.println("DeleteAll----->>"+uid);
        if (cartService.remove(new QueryWrapper<Cart>().eq("uid",uid))){
            modelAndView.setViewName("redirect:/cart/CartSelect.do");
        }else {
            modelAndView.setViewName("redirect:/cart");
        }
        return modelAndView;
    }
//增加单项
    @ResponseBody
    @RequestMapping("/CartAdd.do")
    private ModelAndView carAdd(Integer pid,Cart cart, HttpServletRequest httpServletRequest, HttpSession session, ModelAndView modelAndView)  throws Exception{
//        1，查询对象 QueryWrapper   2，找是否购物车有他的查询对象，3，oldCount获得当前商品数量
//      迭代器  但是首先需要判断这个用户有没有登录
        if (null ==session.getAttribute("user")){
            modelAndView.setViewName("login");
            return modelAndView;
        }
        User user = (User) session.getAttribute("user");
        cart.setUid(user.getUid());
        cart.setPid(pid);
//        主菜：
        QueryWrapper<Cart> hasIt = new QueryWrapper<Cart>();
        hasIt.eq("pid", pid)
                .eq("uid",user.getUid());
        if (cart.selectOne(hasIt) != null) {
//            3，oldCount获得当前商品数量
            Cart temp = cart.selectOne(hasIt);
            Integer oldCount = temp.getCamount();
            //  更新+1 update amount set count=count+1 where id=#{id}
            UpdateWrapper<Cart> cartUpdateWrapper = new UpdateWrapper<>();
            cartUpdateWrapper.eq("cid", temp.getCid()).set("camount", oldCount + 1);
//            更新总价
            cart.update(cartUpdateWrapper);
        } else {
            cart.insert();
        }

        Product product = new Product();
        String Pname = product.selectOne(new QueryWrapper<Product>().eq("pid", pid)).getPname();
        httpServletRequest.setAttribute("goodsName",Pname);
        modelAndView.setViewName("index");
        return modelAndView;
    }
}

